package com.beiding.pojo;

import com.beiding.utils.ResourceUtils;
import com.beiding.utils.TaskUtils;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.util.Assert;

import java.io.File;
import java.io.IOException;

@Getter
@Setter
@Document
public class StaticResource {


    //本地资源路径
    //private static final File parent = new File("C:\\Users\\dinglei\\Desktop\\images");
   private static final File parent = new File("/tmp/pics");

    static {

        if (!parent.exists()) {
            parent.mkdirs();
        }

    }

    @Id
    private String id;

    private String holderId;

    //文件名
    private String fileName;

    public File absolutePathFile() {
        Assert.notNull(fileName, "未指定静态资源文件名");
        Assert.notNull(id, "静态资源文件尚未持久化");

        //直接使用id作为文件id
        return new File(parent, id);
    }

    public String getId() {
        return id;
    }

    void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getFileName() {
        return fileName;
    }

    //资源是否已经被认领.如果被认领则不在换代中移除
    private boolean claimed;

    void persistent() {
        File loc = null;

        String[] cs = null;
        try {
            loc = absolutePathFile();

            doPersistent(loc);

            String[][] cpcs = {cs};
            final File cploc = loc;

            TaskUtils.execute(()->{
                try {
                    cpcs[0] = ResourceUtils.compress(cploc);
                } catch (IOException e) {

                }
            });

        } catch (IOException e) {
            if (loc != null && loc.exists()) {
                loc.delete();
            }
            throw new RuntimeException(e);
        }
    }

    protected void doPersistent(File loc) throws IOException {
        throw new RuntimeException("不支持的操作");
    }


}
